import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized, ResolveStart } from '@angular/router';
import { filter } from 'rxjs/operators';
import { PagesService } from 'services/pages.service';
import { UtilService } from 'services/util.service';
import { SocketService } from 'services/socket.service';
import { fromEvent } from 'rxjs';
import axios from 'axios';
import {
  NzDropdownContextComponent,
  NzDropdownService
} from 'ng-zorro-antd';
declare var layui: any;
declare var layer: any;
declare var $: any;

@Component({
  selector: 'app-perform',
  templateUrl: './perform.component.html',
  styleUrls: ['./perform.component.scss']
})
export class PerformComponent implements OnInit {

  constructor(public router: Router, private http: HttpClient, private dropdownService: NzDropdownService, public interfaceService: PagesService, public utilService: UtilService) { }

  infoWidth;

  ngOnInit() {
    this.interfaceService.loadClose();
    this.directory();
    this.infoWidth = $('.info_left_top').width() - 10 + 'px';
    console.log(this.infoWidth, 'this.infoWidth', $('.info_left_top').width());
    // 页面宽度变化监听
    fromEvent(window, 'resize').subscribe((event) => {
      var liWidth = $('.info_left_top').width();
      this.infoWidth = liWidth - 10 + 'px';
      console.log(liWidth);
    });

    layui.use('code', (obj) => {
      // layui.code();
      /*  layui.code({
         about: false, //不显示右上角 layui.code
         // skin: 'notepad' //设置显示风格
       }); */
    });
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd))
      .subscribe((event) => {
        const tabUrl = window.location.pathname.substring(10, window.location.pathname.length);//选项卡路由地址
        const tabTitle = localStorage.getItem('tabTitle')//当前模块权限名称
        const isRoute = localStorage.getItem('isRoute');//当前模块打开状态
        console.log(tabUrl,tabTitle,isRoute)
        $(window).resize();
        $('.layui-table-tips .layui-layer-content i.layui-icon-close').click();
        if(tabUrl==='/system/setting/perform'){
          if(JSON.stringify(this.isPathJson) !== '{}'){
            this.isLog();
          }
        }else{
          clearInterval(this.intervalPerform);
        }

      });
  }

  checked = false
  address = []//当前目录（层级）
  folderList = []//当前目录下的列表（文件+文件夹）
  folderName = '';//当前目录名称
  folderPath = '';//当前目录地址
  perform = false;// 开启执行
  write = false;// 开启写入
  /**
   * 查询当前目录
   * 初始化当前目录传空为查询根目录
   * 非初始化传相应地址查询对应目录（右侧目录层级点击使用）
   * 也可查询上一级目录（传递当前目录及上一层参数）
   * @param fullPathName 当前目录
   * @param moveUp 是否上一层级
   */
  directory(fullPathName?, moveUp?) {
    const json = {
      catalogue: fullPathName == undefined ? '' : fullPathName,
      moveUp: moveUp == undefined ? '' : moveUp
    }
    this.interfaceService.postPage("/transfer/operate/getjoblistdirectory", json).subscribe((data: any) => {
      if (data.code == 200) {
        this.address = data.object;
        this.folderName = data.object[data.object.length - 1].showName;
        this.folderPath = data.object[data.object.length - 1].catalogue;
        this.getdataxjoblist(data.object[data.object.length - 1].catalogue);
      } else {
        layer.msg(data.message);
      }
    });
  }

  /**
   * 根据当前目录访问目录下文件列表
   * @param catalogue 目录地址对象
   * @param moveUp 是否上一层级（暂时无用）
   */
  getdataxjoblist(catalogue, moveUp?) {
    const json = {
      catalogue: catalogue,
      moveUp: moveUp == undefined ? '' : moveUp
    }
    this.interfaceService.postPage("/transfer/operate/getdataxjoblist", json).subscribe((data: any) => {
      if (data.code == 200) {
        this.folderList = data.object;
      } else {
        layer.msg(data.message);
      }
    });
  }

  /**
   * 双击文件查看内容日志
   */
  isPathJson = {};//定时请求接口参数
  isName = '';//当前查看文件名称
  infoText = '';//文件内容信息
  logText = '';//文件日志信息
  infoLog(list) {
    this.isName = '';
    this.infoText = '';
    this.logText = '';
    clearInterval(this.intervalPerform);
    this.isName = list.fileName;
    this.isPathJson = {
      fullPathName: list.fullPathName
    };
    axios({
      method: 'post',
      url: '/transfer/operate/dataxjsonfileview',
      data: this.isPathJson,
      responseType: 'arraybuffer',
    }).then(res => {
      const datas = res.data
      let blob = new Blob([datas], { type: 'text/html' });
      let objectUrl = URL.createObjectURL(blob);
      this.infoText = $.ajax({ url: objectUrl, async: false }).responseText;
      this.isLog();
    })
  }

  intervalPerform
  isLog() {
    this.intervalPerform = setInterval(() => {
      axios({
        method: 'post',
        url: '/transfer/operate/dataxjsonlogview',
        data: this.isPathJson,
        responseType: 'arraybuffer',
      }).then(res => {
        const datas = res.data
        let blob = new Blob([datas], { type: 'text/html' });
        let objectUrl = URL.createObjectURL(blob);
        this.logText = $.ajax({ url: objectUrl, async: false }).responseText;
        // console.log(this.logText, 'this.logText', new Date())
        setTimeout(() => {
          $('#logText').scrollTop($('#logText')[0].scrollHeight);
        }, this.utilService.setTime1);
        // window.open(objectUrl);
        this.interfaceService.postPage("/transfer/operate/dataxjsonrunstatus", this.isPathJson).subscribe((data2: any) => {
          if (!data2.object) {
            clearInterval(this.intervalPerform);
          }
        });
      })
    }, 2000);
  }


  performList = [];//执行多选列表
  performCheck(value: string[]): void {
    this.performList = value;
    console.log(value);
  }

  /**
   * 确定执行
   */
  performSub() {
    if (this.performList.length > 0) {
      this.interfaceService.postPage("/transfer/operate/executedataxjson", { fullPathNames: this.performList }).subscribe((data: any) => {
        layer.msg(data.message);
        if (data.code == 200) {
          this.perform = false;
          this.performList = []
        }
      });
    } else {
      layer.msg('未正确选择执行数据！');
    }
  }

  editInfo = {}//当前修改信息
  dropdown: NzDropdownContextComponent;
  /**
   * 鼠标右击修改备注
   */
  contextMenu($event: MouseEvent, template: TemplateRef<void>, editInfo) {
    this.editInfo = JSON.parse(JSON.stringify(editInfo));
    this.dropdown = this.dropdownService.create($event, template);
  }

  dropdownClose() {
    this.dropdown.close();
  }

  remarks = false;
  remarksOpen() {
    this.dropdownClose();
    this.remarks = true;
  }

  remarksClose() {
    this.remarks = false;
  }

  /**
   * 修改备注
   */
  isRemarks = localStorage.getItem('isRemarks');
  editRemarks() {
    this.interfaceService.postPage("/transfer/operate/updatedataxjsonmess", this.editInfo).subscribe((data: any) => {
      layer.msg(data.message);
      if (data.code == 200) {
        for (var i = 0; i < this.folderList.length; i++) {
          if (this.folderList[i]['fullPathName'] === this.editInfo['fullPathName']) {
            this.folderList[i]['remarks'] = this.editInfo['remarks'];
          }
        }
        localStorage.setItem('isRemarks', 'isRemarks');
        this.isRemarks = 'isRemarks';
        this.remarksClose();
      }
    });
  }

  remarksWrite() {
    this.interfaceService.postPage("/transfer/operate/writedataxjsonmess", {}).subscribe((data: any) => {
      layer.msg(data.message);
      if (data.code == 200) {
        localStorage.setItem('isRemarks', '');
        this.isRemarks = '';
      }
    });
  }



}
